<template>
  <el-dialog
    :title="addDepdsForm.id ? '编辑部门': '新增部门'"
    :visible="dialogVisible"
    width="60%"
    @close="ondelS"
  >
    <el-form ref="form" :model="addDepdsForm" :rules="addDeptsRormRules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="addDepdsForm.name" placeholder="长度在 1 到 10 个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="addDepdsForm.code" placeholder="长度在 1 到 10 个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="addDepdsForm.manager" placeholder="请选择负责人" @focus="ListOfPrincipals">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="addDepdsForm.introduce" placeholder="长度在 1 到 50 个字符" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('input',false)">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getdepartments, postAddDepartment, getAddDepartmenByid, getAddModify } from '@/api/departments.js'
import { getListSimple } from '@/api/employees.js'
export default {
  model: {
    prop: 'dialogVisible'
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    nodeName: {
      type: Object,
      required: true
    }
  },
  data() {
    const validatorBack = async(rule, value, callback) => {
      // 定义一个公用的变量
      let flag = false
      if (this.addDepdsForm.id) {
        // 获取所有部门
        const res = await getdepartments()
        // 根据pid（pid就是父亲的pid,同级下的子级都是有相同的pid）筛选同级部门， 并排除自己
        const deptsDd = res.depts.filter(item => item.pid === this.nodeName.pid && item.id !== this.nodeName.id)
        flag = deptsDd.some(item => item.code === value)
      } else {
        if (!this.nodeName.children) return callback()
        flag = this.nodeName.children.some(item => item.name === value)
      }
      if (flag) {
        callback(new Error('已经存在' + value + '，不能重复添加'))
      } else {
        callback()
      }
    }
    const valiintroduceBack = async(rule, value, callback) => {
      const res = await getdepartments()
      let treeCote = false
      if (this.addDepdsForm.id) {
        const deptsDd = res.depts.filter(item => item.code !== this.nodeName.code)
        treeCote = deptsDd.some(item => item.code === value)
      } else {
        treeCote = res.depts.some(item => item.code === value)
      }
      if (treeCote) {
        callback(new Error('已经存在' + value + '编码，不能重复添加'))
      }
      callback()
    }
    return {
      addDepdsForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      addDeptsRormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' },
          { validator: validatorBack, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' },
          { validator: valiintroduceBack, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }

        ]
      },
      options: []
    }
  },

  created() {

  },

  methods: {
    // 关闭弹框
    ondelS() {
      this.$emit('input', false)
      this.$refs.form.resetFields()
      this.addDepdsForm = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      }
    },
    // 获取简单列表
    async ListOfPrincipals() {
      const res = await getListSimple()
      console.log(res)
      this.options = res
    },
    // 确定表单
    async onSave() {
      await this.$refs.form.validate()
      try {
        if (this.addDepdsForm.id) {
          await getAddModify(this.addDepdsForm)
          this.$emit('edit-success')
          this.$message.success('恭喜你，修改成功')
        } else {
          this.addDepdsForm.pid = this.nodeName.id
          await postAddDepartment(this.addDepdsForm)
          this.$emit('on-success')
          this.$message.success('恭喜你，添加成功')
        }
        this.ondelS() // 关闭弹窗
      } catch (err) {
        this.$message.error('失败了')
      }
    },
    // 查看部门，并修改
    async getDeptsInfo(id) {
      const res = await getAddDepartmenByid(id)
      this.addDepdsForm = res
    }
  }
}
</script>

<style scoped lang='less'>

</style>
